package top.hcode.hoj.service.signup.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.hcode.hoj.common.exception.StatusFailException;
import top.hcode.hoj.common.exception.StatusForbiddenException;
import top.hcode.hoj.common.result.CommonResult;
import top.hcode.hoj.mapper.SignUpContestMapper;
import top.hcode.hoj.mapper.TeamInfoMapper;
import top.hcode.hoj.mapper.UserInfoMapper;
import top.hcode.hoj.pojo.dto.TeamInfoDTO;
import top.hcode.hoj.pojo.entity.signup.SignUpContest;
import top.hcode.hoj.pojo.entity.signup.TeamInfo;
import top.hcode.hoj.pojo.entity.user.UserInfo;
import top.hcode.hoj.pojo.vo.TeamInfoVO;
import top.hcode.hoj.service.signup.TeamInfoEntityService;
import top.hcode.hoj.shiro.AccountProfile;
import top.hcode.hoj.utils.Constants;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 76004
 * @apiNote
 * @date 2023/4/10 14:12
 */
@Service
public class TeamInfoEntityServiceImpl implements TeamInfoEntityService {

    @Autowired
    private SignUpContestMapper signUpContestMapper;

    @Autowired
    private TeamInfoMapper teamInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;


    @Override
    public CommonResult<List<TeamInfoVO>> selectWaitingReviewTeamInfoPage(Long cid, Integer pageSize, Integer pageNum) throws StatusForbiddenException, StatusFailException {
        SignUpContest contest = signUpContestMapper.selectById(cid);

        if(contest == null){
            throw new StatusFailException("没有这场比赛");
        }

        AccountProfile accountProfile = (AccountProfile) SecurityUtils.getSubject().getPrincipal();

        boolean isRoot = SecurityUtils.getSubject().hasRole("root");

        if(!isRoot){
            throw new StatusForbiddenException("您没有权限获取该名单!");
        }
        List<TeamInfo>teamInfos = teamInfoMapper.selectList(new QueryWrapper<TeamInfo>().eq("sign_up_contest_id",cid)
                .eq("status",Constants.Team.APPLY_FOR_UPDATE));
        List<TeamInfoVO>teamInfoVos = new ArrayList<>();
        BeanUtil.copyProperties(teamInfos,teamInfoVos,"password");
        return CommonResult.successResponse(teamInfoVos);
    }

    /***
     * 查询用户在当前比赛的组队信息
     * @param cid
     * @return
     */
    @Override
    public CommonResult<List<TeamInfoVO>> getTeamInfoByUsernameFromContestId(Long cid) throws StatusFailException {
        //获取当前登录的用户
        AccountProfile userRolesVo = (AccountProfile) SecurityUtils.getSubject().getPrincipal();
        // 获取本场比赛的状态
        SignUpContest contest = signUpContestMapper.selectById(cid);
        if(contest == null){
            throw new StatusFailException("报名列表不存在");
        }

        List<TeamInfoVO> teamInfoVOS = teamInfoMapper.selectList(new QueryWrapper<TeamInfo>().eq("sign_up_contest_id",contest.getId())
                .like("users_name",userRolesVo.getUsername()+"-%")).stream().filter(entity->{
            //是不是队长
            if(userRolesVo.getUsername().equals(entity.getUsersName().split("-")[0])){
                return true;
            }else{
                return false;
            }
        }).map(entity -> {
            return BeanUtil.copyProperties(entity,TeamInfoVO.class,"password");
        }).collect(Collectors.toList());


        return CommonResult.successResponse(teamInfoVOS);
    }

    /***
     * 获取待审核的报名信息
     * @param cid
     * @param pageSize
     * @param pageNum
     * @return
     * @throws StatusFailException
     * @throws StatusForbiddenException
     */
    @Override
    public CommonResult<IPage<TeamInfo>> getTeamInfoPageByContestId(Long cid, Integer pageSize, Integer pageNum, Integer status) throws StatusFailException, StatusForbiddenException {

        SignUpContest contest = signUpContestMapper.selectById(cid);
        if(contest == null){
            throw new StatusFailException("报名收集表不存在");
        }
        List<TeamInfo>teamInfos = null;
        List<TeamInfoVO>teamInfoVOS = new ArrayList<>();
        if(status == 0){
            return CommonResult.successResponse(teamInfoMapper.selectPage(new Page<TeamInfo>(pageNum,pageSize),
                    new QueryWrapper<TeamInfo>().eq("sign_up_contest_id",cid).orderByAsc("star").orderByDesc("create_time")));
        }else if(status.equals(Constants.Team.PENDING.getStatus())
                || status.equals(Constants.Team.REJECT.getStatus())
                || status.equals(Constants.Team.ACCEPT.getStatus())
                || status.equals(Constants.Team.APPLY_FOR_UPDATE.getStatus())){
            return CommonResult.successResponse(teamInfoMapper.selectPage(new Page<TeamInfo>(pageNum,pageSize),
                    new QueryWrapper<TeamInfo>().eq("sign_up_contest_id",cid).eq("status",status).orderByAsc("star").orderByDesc("create_time")));
        }else{
            throw new StatusFailException("状态码不正确");
        }

//        for(TeamInfo teamInfo:teamInfos){
//            TeamInfoVO teamInfoVO = new TeamInfoVO();
//            BeanUtil.copyProperties(teamInfo,teamInfoVO);
//            teamInfoVO.setCreatTime(teamInfo.getCreateTime());
//            teamInfoVOS.add(teamInfoVO);
//        }
//
//
//        return CommonResult.successResponse(teamInfoVOS);
    }

    @Override
    public CommonResult<TeamInfoVO> getTeamInfoById(Long teamId) throws StatusFailException {
        TeamInfo teamInfo = teamInfoMapper.selectById(teamId);
        if(teamInfo == null){
            throw new StatusFailException("队伍不存在");
        }
        TeamInfoVO teamInfoVO = new TeamInfoVO();
        BeanUtil.copyProperties(teamInfo,teamInfoVO,"password");
        return CommonResult.successResponse(teamInfoVO);
    }

    @Override
    public CommonResult<Void> updateSignUpTable(TeamInfoDTO teamInfoDTO) throws StatusForbiddenException {
        //获取当前登录的用户
        AccountProfile userRolesVo = (AccountProfile) SecurityUtils.getSubject().getPrincipal();

        String[] users = teamInfoDTO.getUsersName().split("-");

        boolean isRoot = SecurityUtils.getSubject().hasRole("root");
        if(!userRolesVo.getUsername().equals(users[0]) && !isRoot){
            throw new StatusForbiddenException("不是你的报名信息");
        }

        SignUpContest contest = signUpContestMapper.selectById(teamInfoDTO.getSignUpContestId());

        //比赛是否结束
        if(new Date().after(contest.getEndTime()) && !isRoot){
            throw new StatusForbiddenException("比赛已结束，不能更改");
        }
        if(teamInfoDTO.getStatus().equals(Constants.Team.ACCEPT.getStatus())){
            throw new StatusForbiddenException("您的申请已通过，请提交更改申请");
        }
        TeamInfo teamInfo = new TeamInfo();
        BeanUtil.copyProperties(teamInfoDTO,teamInfo,"password");

        //判断是否为女队
        String[] genders = teamInfo.getGender().split("-");
        teamInfo.setTeamType(1);
        for(String i:genders){
            if(i.equals("0")){
                teamInfo.setTeamType(0);
                break;
            }
        }

        //队伍名判重
        int count = teamInfoMapper.selectCount(new QueryWrapper<TeamInfo>().eq("sign_up_contest_id",teamInfo.getSignUpContestId()).eq("team_name",teamInfo.getTeamName()));
        if(count > 1){
            throw new StatusForbiddenException("队伍名重复");
        }

        //将比赛与实际用户绑定（如果填写了的话）
        String[] username = teamInfo.getUsersName().split("-");
        //队长一定是当前发起报名的用户
        username[0] = userRolesVo.getUsername();
        if(username[0].equals(username[1]) || (!Objects.equals(username[2], "*") && username[1].equals(username[2])) || username[0].equals(username[2])){
            throw new StatusForbiddenException("队员重复");
        }
        for(String i:username){
            if(!i.equals("*")){
                //用户填写了用户名
                UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("username",i));
                if(userInfo != null) {
                    //增加用户比赛记录(待添加)
                }else{
                    throw new StatusForbiddenException("用户不存在，请检查用户名是否填写正确");
                }
            }
        }
        teamInfo.setStatus(Constants.Team.APPLY_FOR_UPDATE.getStatus());
        teamInfoMapper.updateById(teamInfo);
        return CommonResult.successResponse();
    }


    public CommonResult<Integer> getACTeamCount(Long contestId){
        return CommonResult.successResponse(teamInfoMapper.selectCount(new QueryWrapper<TeamInfo>().eq("sign_up_contest_id",contestId).eq("status",Constants.Team.ACCEPT.getStatus())));
    }
}
